import App from './App'
import {
	$http
} from '@escook/request-miniprogram'
import {
	api
} from '@/utils/api.js'

import {
	profile,
	UserSetting
} from '@/env-config.js';

import {
	XTSerialize
} from '@/utils/XTSerialize.js'

import {
	dapi
} from '@/utils/api-interface.js'

import {
	navHtml
} from '@/utils/navHtml.js'


import store from '@/store/store.js'


uni.$http = $http
// $http.baseUrl = 'https://www.uinav.com'
// $http.baseUrl = 'https://api-hmugo-web.itheima.net'
// $http.header["Content-Type"] = XTSerialize.jsonType
// $http.defaults.headers.common['Content-Type'] = XTSerialize.jsonType;

$http.beforeRequest = function(options) {
	uni.showLoading({
		title: '数据加载中...'
	})
	// console.log(store);
	// console.log(store.state);
	// console.log(store.state.m_user);
	// console.log(store.state.m_user.token);

	if (profile.active === 'dev') {
		//判断当前请求是否为有权限的接口
		if (options.url.indexOf('/my/') !== -1) {
			options.header = {
				// Authorization: store.state.m_user.token,
				token: store.state.m_user.token
			}
		}
	} else {
		options.header["sa-token"] = store.state.m_user.token
	}


	// options.header["Content-Type"] = "application/x-www-form-urlencoded"
	options.header["Content-Type"] = "application/json"
	if (options.url.indexOf('/user/login') !== -1) {
		options.header["Content-Type"] = XTSerialize.formType
	} else if (options.url.indexOf('/wares/download') !== -1) {
		options.header["Content-Type"] = XTSerialize.formType
		XTSerialize.setArrayBuffer(options)
	}
	console.log(options);
}
$http.afterRequest = function(options) {
	uni.hideLoading()
}

// 封装弹框的方法
uni.$showMsg = function(title = '数据请求失败！', duration = 1500) {
	uni.showToast({
		title,
		duration,
		icon: 'none'
	})
}

uni.$api = api
uni.$env = {
	profile,
	UserSetting
}
uni.$dapi = dapi
uni.$serialize = XTSerialize
uni.$navHtml = navHtml

// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'

try {
	function isPromise(obj) {
		return (
			!!obj &&
			(typeof obj === "object" || typeof obj === "function") &&
			typeof obj.then === "function"
		);
	}

	// 统一 vue2 API Promise 化返回格式与 vue3 保持一致
	uni.addInterceptor({
		returnValue(res) {
			if (!isPromise(res)) {
				return res;
			}
			return new Promise((resolve, reject) => {
				res.then((res) => {
					if (res[0]) {
						reject(res[0]);
					} else {
						resolve(res[1]);
					}
				});
			});
		},
	});
} catch (error) {}

const app = new Vue({
	...App,
	store
})
app.$mount()
// #endif

// #ifdef VUE3
import {
	createSSRApp
} from 'vue'

export function createApp() {
	const app = createSSRApp(App)
	app.use(store)
	return {
		app
	}
}
// #endif